/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Jiang Jinxi
 * Date: 2024-09-01
 * Time: 14:10
 */
class MyBlockingQueue{
    private String[] elems = null;
    private volatile int head;
    private volatile int tail;
    private volatile int size = 0;

    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }
    //入队列
    public void put(String elem) throws InterruptedException {
        synchronized(this){
            while(size >= elems.length){
                //队列满了, 进行阻塞等待
                this.wait();
            }
            //将新的元素加入到队列中
            elems[tail] = elem;
            tail++;
            //循环队列
            if(tail >= elems.length){
                tail = 0;
            }
            //更新size的值
            size++;
            //唤醒take的阻塞
            this.notify();
        }
    }
    //出队列
    public String take() throws InterruptedException {
        synchronized (this){
            while(size == 0){
                //队列为空, 进行阻塞等待
                this.wait();
            }
            //将队首元素返回给elem
            String elem = elems[head];
            tail++;
            //循环队列
            if(head >= elems.length){
                head = 0;
            }
            //更新size的值
            size--;
            //唤醒put的阻塞
            this.notify();
            return elem;
        }
    }
}
public class Demo25 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        //生产者
        Thread t1 = new Thread(() -> {
            int i = 1;
            String elem = "aaa";
            while(true){
                try {
                    queue.put(elem);
                    System.out.println("t1生产: " + i);
                    i++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        //消费者
        Thread t2 = new Thread(() -> {
            while(true){
                try {
                    String elem = queue.take();
                    System.out.println("t2消费: " + elem);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
